﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WindowsPhoneRssReader.Models;
using WindowsPhoneRssReader.Utils;

namespace WindowsPhoneRssReader
{
    public partial class ManagerRssPage : PhoneApplicationPage
    {
        public ManagerRssPage()
        {
            InitializeComponent();
            PageTransitionList.Completed += PageTransitionList_Completed;
            Loaded += ManagerRssPage_Loaded;
        }

        void PageTransitionList_Completed(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddRssPage.xaml", UriKind.Relative));
        }

        void ManagerRssPage_Loaded(object sender, RoutedEventArgs e)
        {
            ResetPageTransitionList.Begin();
        }

        private void _buttonAdd_Click(object sender, EventArgs e)
        {
            PageTransitionList.Begin();
        }

        private void _buttonDelete_Click(object sender, EventArgs e)
        {
            var feed = lstFeed.SelectedItem as Feed;
            if (feed == null) return;
            var anser = MessageBox.Show("Do you want to delete " + feed.FeedName + " ?", "", MessageBoxButton.OKCancel);
            if (anser != MessageBoxResult.OK) return;

            var success = XmlAction.DeleteFeedData(feed.Id);
            if (success)
            {

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    XmlAction.DeleteFeed(feed.Id);
                    var feeds = (DataContext as ObservableCollection<Feed>);
                    if (feeds != null) feeds.Remove(feed);
                    var deletesFavrItem = App.RssReader.FavouriteItems.Where(item => item.ParentFeed.Id == feed.Id).ToList();

                    foreach (var item in deletesFavrItem)
                    {
                        App.RssReader.FavouriteItems.Remove(item);
                    }
                    MessageBox.Show("Delete success");
                });

            }
            else
            {
                MessageBox.Show("Failure");
            }

        }

        private void _buttonHome_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_DoubleTap(object sender, GestureEventArgs e)
        {
            lstFeed.SelectedIndex = -1;
        }


    }
}